# -*- coding: utf-8 -*-
from __future__ import with_statement
import positioning
import sysinfo
import appuifw
import sys
import e32
from time import localtime, strftime, gmtime
import btsocket
import location
import os
import ConfigParser

APP_NAME = 'YouLoc'
APP_VERSION = 0.4

"""
Tero Heino, whiz@iki.fi, 2009
"""


class YouLoc:
	cfg_file = 'e:\\youloc.cfg'
	config = None
	t = None
	lock = None
	apo = None
	apid = None
	fix = False
	position_data = None
	previous_position_data = None
	gsm_cell = None
	gpx_logging = None
	gpxfile = None
	
	def __init__ (self):
		self.config = ConfigParser.RawConfigParser()
		
		self.lock = e32.Ao_lock()
		appuifw.app.exit_key_handler = self.quit
		self.t = appuifw.Text()
		appuifw.app.body = self.t
		self.t.clear()

	def init_ui(self):
		appuifw.app.title = u'%s v%.1f' % (APP_NAME, APP_VERSION)
		appuifw.app.screen = 'large'
		appuifw.app.menu = [(u"Run configure", self.configure),(u"Quit", self.quit)]
		
	def read_config(self):
		if ( os.path.isfile(self.cfg_file) ):
			self.config.read(self.cfg_file)
			self.userkey = self.config.get('common', 'userkey') 
			self.apid = self.config.getint('common', 'apid')
			self.gpx_logging = self.config.getboolean('common', 'gpx_logging')
			if self.userkey == None or self.apid == None:
				self.configure()
			self.output(self.userkey)
			self.output(self.apid)
		else:
			self.configure()

	def configure(self):
		apid = None
		userkey = None
		gpx_logging = None
		
		apid = btsocket.select_access_point()
		auth_methods = [u"IMEI",u"USERKEY"]
		
		auth_method = appuifw.selection_list(choices=auth_methods , search_field=0)
		if auth_method == 0:
			userkey = unicode(sysinfo.imei())
		elif auth_method == 1:
			while userkey == None:
				userkey = appuifw.query(u"Your YouLoc userkey", "text")
		
		gpx_choices = appuifw.selection_list(choices=[u"Enable GPX-logging", u"Disable GPX-logging"], search_field=0)
		if gpx_choices == 0:
			gpx_logging = True
		elif gpx_choices == 1:
			gpx_logging = False
		
		try:
			self.config.add_section('common')
			self.config.set('common', 'userkey', userkey)
			self.config.set('common', 'apid', apid)
			self.config.set('common', 'gpx_logging', gpx_logging)
			with open(self.cfg_file, 'wb') as configfile:
			    self.config.write(configfile)
			
		except IOError, e:
			appuifw.note( u'Unable to write to file!', 'error' )
			
		self.apid = apid
		self.userkey = userkey
		self.gpx_logging = gpx_logging
		
	def get_internets(self):
		self.apo = btsocket.access_point(self.apid)

	def get_satellites(self):
		positioning.set_requestors([{"type":"service", "format":"application", "data":"YouLoc"}])
		positioning.position(	course=1,
					satellites=1,
					callback=self.processLocationData,
					interval=1000000,
					partial=1)
	
	def init_gpx(self):
		try:
			self.gpxfile = file('E:\\YouLoc-'+strftime('%y%m%d-%H%M')+'.gpx','w')
			self.gpxfile.write('<?xml version="1.0" encoding="UTF-8"?>\n')
			self.gpxfile.write('<gpx version="1.0" creator="YouLoc PyS60 - http://youloc.net">\n')
			self.gpxfile.write('<trk>\n<trkseg>\n')
		except IOError, e:
			self.gpx_logging = False
			appuifw.note( u'Unable to open GPX-logfile!', 'error' )

	def output(self, msg, clearscreen = False):
		""" Output formatted message wit"""
		if clearscreen:
			self.t.clear()
			self.t.add(u"%s\n--------\n" % strftime("%H:%M:%S", localtime() ) )
		self.t.add(u"%s\n" % msg)


	def run(self):
		self.read_config()
		self.init_ui()
		self.get_internets()
		self.get_satellites()
		if self.gpx_logging == True:
			self.init_gpx()
		self.output('%s v%.1f' % (APP_NAME, APP_VERSION))
		self.output("connecting..")
		while True:
			self.lock.wait()
	
		self.output(u"Finished..")

	def has_fix(self):
		if self.position_data:
			data = self.position_data
			if "position" in data:
				if str(data['position'].get('latitude', 'nan')).lower() != "nan":
					return True
		return False

# latitude altitude vertical_accuracy longitude horizontal_accuracy

	def processLocationData(self, data):
		self.position_data = data
		self.fix = self.has_fix()
		self.gsm_cell = location.gsm_location()
		
		if self.fix:
			# {’satellites’: {’horizontal_dop’: 2.34999990463257, ’used_satellites’: 5, ’verti
			# cal_dop’: 2.29999995231628, ’time’: 1187167353.0, ’satellites’: 11, ’time_dop’:
			# 1.26999998092651}, ’position’: {’latitude’: 60.217033666473, ’altitude’: 42.0, ’
			# vertical_accuracy’: 58.0, ’longitude’: 24.878942093007, ’horizontal_accuracy’: 4
			# 7.531005859375}, ’course’: {’speed’: 0.0500000007450581, ’heading’: 68.959999084
			# 4727, ’heading_accuracy’: 359.989990234375, ’speed_accuracy’: NaN}
			if self.gpx_logging == True:
				self.gpxfile.write('<trkpt lat="'+str(data['position']['latitude'])+'" lon="'+str(data['position']['longitude'])+'">')
				self.gpxfile.write('<ele>'+str(data['position']['altitude'])+'</ele>')
				if 'course' in data:
					self.gpxfile.write('<course>'+str(data['course']['heading'])+'</course><speed>'+str(data['course']['speed'])+'</speed>')
				self.gpxfile.write('<time>'+strftime('%Y-%M-%dT%H:%m:%sZ',gmtime())+'</time>')
				self.gpxfile.write('<sat>'+str(data['satellites']['used_satellites'])+'</sat>')
				self.gpxfile.write('<hdop>'+str(data['satellites']['horizontal_dop'])+'</hdop><vdop>'+str(data['satellites']['vertical_dop'])+'</vdop>')
				self.gpxfile.write('</trkpt>\n')
				self.gpxfile.flush()
			self.postData()
			#self.t.add(u"%s\n\n%s\n\n" % ( self.position_data["position"], self.position_data["course"]) )

	def postData(self):
		btsocket.set_default_access_point(self.apo)
		host = "youloc.net"
		port = 80
		lat = self.position_data['position']['latitude']
		lon = self.position_data['position']['longitude']
		alt = self.position_data['position']['altitude']
		speed = self.position_data['course']['speed']
		if self.previous_position_data != None:
			if "%.4f" % lat == "%.4f" % self.previous_position_data['position']['latitude'] and "%.4f" % lon == "%.4f" % self.previous_position_data['position']['longitude']:
				return
			
		url = "/logger.php?userkey=%s&lat=%s&lon=%s&alt=%s&speed=%s" % (self.userkey, lat, lon, alt, speed)
		if self.gsm_cell != None:
			mcc = self.gsm_cell[0]
			mnc = self.gsm_cell[1]
			lac = self.gsm_cell[2]
			cid = self.gsm_cell[3]
			url = "/logger.php?userkey=%s&lat=%s&lon=%s&alt=%s&speed=%s&cell=%s&mcc=%s&mnc=%s&lac=%s" % (self.userkey, lat, lon, alt, speed, cid, mcc, mnc, lac)
			
		s = btsocket.socket(btsocket.AF_INET, btsocket.SOCK_STREAM)
		s.connect( (host, port) )
		s.send("GET %s HTTP 1.1\nHost: %s\n\n" % (url, host))
		s.close()
		
		self.output("Latitude: %.2f\nLongitude: %.2f\nAltitude: %d\nSpeed: %d\n\n" % (lat,lon,alt,speed), True)
		if self.gsm_cell != None:
			self.output("CellID: %d\nMCC: %d\nMNC: %d\nLAC: %d\n" %(cid, mcc, mnc, lac))
        
		self.previous_position_data = self.position_data
        
	    
	def quit (self):
		if self.gpx_logging == True:
			self.gpxfile.write('</trkseg>\n</trk>\n</gpx>')
			self.gpxfile.close()
		self.lock.signal()
		appuifw.app.set_exit()
				
			
			
if __name__ == "__main__":
	YL = YouLoc()
	YL.run()
